﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace Common
{
    public class DataTableHelper
    {
        /// <summary>
        /// 将datatable转换为对象集合（只适用对象的属性都是基本类型的数据）
        /// </summary>
        /// <typeparam name="T">要被转换的类型</typeparam>
        /// <param name="dt">表</param>
        /// <returns>对象的list集合</returns>
        public static List<T> Table2List<T>(DataTable dt) where T:class,new ()
        {
            if (dt == null || dt.Rows.Count < 1)
            {
                return null;
            }
            PropertyInfo[] props = typeof(T).GetProperties();
            List<T> list = new List<T>();
            foreach (DataRow item in dt.Rows)
            {
                T t = new T();
                for (int i = 0; i < props.Length; i++)
                {
                    var pi = props[i];
                    if (dt.Columns.Contains(pi.Name))
                    {
                        pi.SetValue(t, Convert.ChangeType(item[pi.Name], pi.PropertyType), null);
                    }
                }
                list.Add(t);
            }
            return list;
        }
    }
}
